﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Configuration;
using MyWebPagesStarterKit.Rewriter;
using System.Collections.Specialized;
using MyWebPagesStarterKit.Controls;
using MyWebPagesStarterKit;

public partial class SectionControls_News : SectionControlBaseClass
{
    private News _section;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            EnsureID();
            valHeadlineRequired.ValidationGroup = ID;
            btnSaveDetails.ValidationGroup = ID;
        }
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        updateViews();
    }

    protected void gvNewsListEdit_RowCommand(object source, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "edit_entry":
                ViewState["Edit"] = gvNewsListEdit.DataKeys[int.Parse(e.CommandArgument.ToString())].Value;
                break;
            case "delete_entry":
                _section.Entries.Rows.Remove(_section.GetEditEntry(gvNewsListEdit.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString()));
                _section.Entries.AcceptChanges();
                _section.SaveData();
                break;
        }
    }

    protected void gvNewsList_RowCommand(object source, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "show_details")
        {
            ViewState["detail"] = gvNewsList.DataKeys[int.Parse(e.CommandArgument.ToString())].Value;
        }
    }

    protected void srcNewsList_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        e.ObjectInstance = _section;
    }

    protected void btnNewEntry_Click(object sender, EventArgs e)
    {
        ViewState["Edit"] = "new";
    }

    protected void btnSaveDetails_Click(object sender, EventArgs e)
    {
        DataRow row;
        if (ViewState["Edit"].ToString() == "new")
        {
            row = _section.Entries.NewRow();
            row["Guid"] = Guid.NewGuid();
            _section.Entries.Rows.Add(row);
        }
        else
        {
            row = _section.GetEditEntry(ViewState["Edit"].ToString());
        }

        if (row != null)
        {
            _section.PageID = new WebPage(Request["pg"]).PageId;
            row["Title"] = txtHeadline.Text.Trim();
            row["Html"] = txtNewsHtml.Text.Trim();
            row["Keywords"] = txtKeyword.Text;
            row["RewriteUrl"] = string.Format("{0}.aspx", TextFormatter.CreateFriendlyUrl(txtHeadline.Text).ToLower());
            row["Description"] = txtDescription.Text.Trim();

            //adding datetime (only for correct sorting of news (Time is not shown)
            DateTime ShowFrom = new DateTime(dteDateFrom.DateValue.Year, dteDateFrom.DateValue.Month, dteDateFrom.DateValue.Day);
            ShowFrom = ShowFrom.AddHours(DateTime.Now.Hour);
            ShowFrom = ShowFrom.AddMinutes(DateTime.Now.Minute);
            ShowFrom = ShowFrom.AddSeconds(DateTime.Now.Second);

            row["StartDate"] = ShowFrom;
            if (txtDateUntil.Text != string.Empty)
                row["EndDate"] = dteDateUntil.DateValue;
            else
                row["EndDate"] = DBNull.Value;
            row.AcceptChanges();

            _section.SaveData();
        }

        ViewState["Edit"] = null;
    }

    protected void btnCancelDetails_Click(object sender, EventArgs e)
    {
        ViewState["Edit"] = null;
    }

    public override ISection Section
    {
        set
        {
            if (value is News)
                _section = (News)value;
            else
                throw new ArgumentException("Section must be of type News");
        }
        get { return _section; }
    }

    public override bool HasAdminView
    {
        get { return true; }
    }

    public override string InfoUrl
    {
        get
        {
            string lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            if (File.Exists(HttpContext.Current.Server.MapPath(string.Format("Documentation/" + lang + "/quick_guide.html"))))
            {
                return "Documentation/" + lang + "/quick_guide.html#news-list";
            }
            else
            { return "Documentation/en/quick_guide.html#news-list"; }
        }
    }

    private void updateViews()
    {
        if (ViewMode == ViewMode.Edit)
        {
            if (ViewState["Edit"] != null)
            {
                multiview.SetActiveView(editDetailsView);

                if (ViewState["Edit"].ToString() == "new")
                {
                    dteDateFrom.DateValue = DateTime.Today;
                    txtHeadline.Text = string.Empty;
                    txtNewsHtml.Text = string.Empty;
                }
                else
                {
                    DataRow entry = _section.GetEditEntry(ViewState["Edit"].ToString());
                    dteDateFrom.DateValue = (DateTime)entry["StartDate"];
                    if (entry["EndDate"] != DBNull.Value)
                        dteDateUntil.DateValue = (DateTime)entry["EndDate"];
                    txtHeadline.Text = (string)entry["Title"];
                    txtNewsHtml.Text = (string)entry["Html"];
                    txtKeyword.Text = (string)entry["Keywords"];
                    txtDescription.Text = (string)entry["description"];
                }
            }
            else
            {
                gvNewsListEdit.DataSource = _section.GetEntriesEdit();
                gvNewsListEdit.DataBind();
                multiview.SetActiveView(editView);
            }
        }
        else
        {
            //Rewrite section 
            if (Request["details"] != null)
            {
                multiview.SetActiveView(SingleView);
                DataRow row = _section.GetEditEntryReadOnly(Request["details"]);

                if(row!=null)
                    if (!string.IsNullOrEmpty(row["StartDate"].ToString()))
                        litStartDate.Text = ((DateTime)row["StartDate"]).ToShortDateString();
                    
                    litTitle.Text = (string)row["Title"];
                    litHtml.Text = (string)row["Html"];

                    //Need Title, Description and Keywords in DataTable "Entries" from Section.
                    SectionHeaderUtils.GenerateMeta(this.Page,(string)row["Title"],(string)row["Description"], (string)row["Keywords"]);
            }
            else
            {
                multiview.SetActiveView(readonlyView);
                gvNewsList.DataSource = _section.GetEntriesReadonly();
                gvNewsList.DataBind();
            }
        } 
        
   
    }

    protected string GetPrefix(string link)
    {
        return string.Format("{0}{1}", SectionRewriter.GetPrefix(_section.GetType().Name), link);       
    }
}
